package pool

import (
	"net/http"
	"sync"
)

var (
	defaultPool = &Pool{}
	globalPool  = defaultPool
)

func Global() *Pool     { return globalPool }
func SetGlobal(p *Pool) { globalPool = p }
func New() *Pool        { return &Pool{} }

type Pool struct {
	pool sync.Pool
}

func (p *Pool) Get() *http.Client {
	if c, ok := p.pool.New().(*http.Client); ok {
		return c
	}
	return &http.Client{}
}

func (p *Pool) GetWithTransport(tr http.RoundTripper) *http.Client {
	c := p.Get()
	c.Transport = tr
	return c
}

func (p *Pool) Recycle(c *http.Client) {
	c.Transport = nil
	c.CheckRedirect = nil
	c.Jar = nil
	c.Timeout = 0
	p.pool.Put(c)
}
